import os
from PIL import Image
import shutil

def ensure_dir(directory):
    """确保目录存在，如果不存在则创建"""
    if not os.path.exists(directory):
        os.makedirs(directory)

def compress_image(input_path, output_path, quality=8):
    """压缩单个图片
    
    Args:
        input_path: 输入图片路径
        output_path: 输出图片路径
        quality: 压缩质量，范围1-100
    """
    try:
        # 确保输出目录存在
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        
        # 打开图片
        with Image.open(input_path) as img:
            # 保存压缩后的图片
            img.save(output_path, quality=quality, optimize=True)
            
        # 获取原始文件大小和压缩后文件大小
        original_size = os.path.getsize(input_path)
        compressed_size = os.path.getsize(output_path)
        
        # 计算压缩率
        compression_ratio = (1 - compressed_size / original_size) * 100
        
        print(f"压缩完成: {os.path.basename(input_path)}")
        print(f"原始大小: {original_size/1024:.2f}KB")
        print(f"压缩后大小: {compressed_size/1024:.2f}KB")
        print(f"压缩率: {compression_ratio:.2f}%")
        print("-" * 50)
        
    except Exception as e:
        print(f"处理图片 {input_path} 时出错: {str(e)}")

def process_directory(input_dir, output_dir):
    """处理整个目录下的图片
    
    Args:
        input_dir: 输入目录
        output_dir: 输出目录
    """
    # 确保输出根目录存在
    ensure_dir(output_dir)
    
    # 遍历输入目录
    for root, dirs, files in os.walk(input_dir):
        # 计算对应的输出目录路径
        relative_path = os.path.relpath(root, input_dir)
        current_output_dir = os.path.join(output_dir, relative_path)
        
        # 确保当前输出目录存在
        ensure_dir(current_output_dir)
        
        # 处理当前目录下的所有文件
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.webp')):
                input_path = os.path.join(root, file)
                output_path = os.path.join(current_output_dir, file)
                compress_image(input_path, output_path)
            else:
                # 对于非图片文件，直接复制
                input_path = os.path.join(root, file)
                output_path = os.path.join(current_output_dir, file)
                shutil.copy2(input_path, output_path)

if __name__ == "__main__":
    input_directory = "images"
    output_directory = "images_mini"
    
    # 获取脚本所在目录的绝对路径
    script_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 构建完整的输入和输出路径
    input_directory = os.path.join(script_dir, input_directory)
    output_directory = os.path.join(script_dir, output_directory)
    
    print(f"开始处理图片压缩...")
    print(f"输入目录: {input_directory}")
    print(f"输出目录: {output_directory}")
    print("-" * 50)
    
    process_directory(input_directory, output_directory)
    print("所有图片处理完成！")
